package ssn.common.interceptor;

import java.util.Map;

import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import ssn.common.menu.service.MenuService;
import ssn.login.vo.LoginInfoVO;
import egovframework.rte.fdl.cmmn.exception.EgovBizException;
import egovframework.rte.fdl.string.EgovStringUtil;

public class SsnInterceptor extends HandlerInterceptorAdapter{

	@Inject
	private Provider<LoginInfoVO> loginSessionInfo;
	
	@Resource(name = "menuService")
	private MenuService menuService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// TODO Auto-generated method stub
		
		/**
		 * 로그인 체크
		 */
		if(request.getServletPath().indexOf("/login") == -1){
			String referer = request.getRequestURI();
			if(request.getServletPath().indexOf("/main") > -1 
					|| request.getServletPath().indexOf("Excel") > -1
					|| request.getServletPath().indexOf("login") > -1
					){
				referer = "";
			}
			if(!loginSessionInfo.get().isLoginCheck()){
				String param = "";
				if(EgovStringUtil.isNotEmpty(referer)){
					param = "?referer="+referer;
				}
				response.sendRedirect(request.getContextPath()+"/login/loginForm.do"+param);
				return false;
			}
		}
		
		/**
		 * Url base 권한 체크 관리자 페이지
		 * 로직 개선 필요. 
		 */
		if(request.getServletPath().toLowerCase().indexOf("servicearea/admin") > -1 || 
				request.getServletPath().indexOf("useDrugManage") > -1 ||
				request.getServletPath().indexOf("zone") > -1
				){
			if(!loginSessionInfo.get().isAdmin()){
				throw new EgovBizException("권한이 없습니다.");
			}
		}
		
		/**
		 * 메뉴 & 네비 & menu On
		 * Exception 발생시 메뉴가 보이게 하기위해 pre 에서 처리함.
		 */
		if(request.getServletPath().indexOf("/login") == -1){
			Map resultMap = menuService.getTopMenu(loginSessionInfo.get().getSsa_user_auth(), request);
			request.setAttribute("topMenu", resultMap.get("topMenu"));
			request.setAttribute("nowMenuGroup", resultMap.get("nowMenuGroup"));
			request.setAttribute("navi", resultMap.get("navi"));
		}
		
		return super.preHandle(request, response, handler);
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		
		
		
		super.postHandle(request, response, handler, modelAndView);
	}
}
